﻿using System;
using Epm.AppLogic.Framework;
using msBsc.Xsd.DataTds;
using System.Data;

namespace msBsc.AppLogic.DataAlc
{
    public class CBizShpChargeTradingLog : CustBizObject
    {
        private CDmShpChargeTradingLog m_CDmShpChargeTradingLog = new CDmShpChargeTradingLog();
        private CDmShpChargeTradingLog oDmShpChargeTradingLog
        {
            get { return m_CDmShpChargeTradingLog; }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public CBizShpChargeTradingLog()
            : base()
        {
            this.DataObj = new CDbAccess();
            this.DataObj.Init(this.m_CDmShpChargeTradingLog.SHP_CHARGE_TRADING_LOG);
            this.TableName = this.DataObj.TableName;
            this.DataObj.KeyField = this.DataObj.Fields["CHARGE_TRADING_ID"]; 
        }

        /// <summary>
        /// 新增记录前的处理
        /// </summary>
        /// <param name="drw">新增数据行</param>
        /// <returns>true/false</returns>
        /// <remarks>
        /// 生成ID值
        /// </remarks>
        protected override bool BeforeRowAdded(DataRow drw)
        {
            if (drw[this.KeyFieldName].ToString().Length < 10)
            {
                drw[this.KeyFieldName] = this.DataObj.NewID();
            }
            if (drw["TRADING_NO"].ToString() == string.Empty)
            {
                drw["TRADING_NO"] = GetNewTradingNo();// msBsc.SvRef.ApplicationConst.Const.GetNewSerialNo("TRADING_NO", System.DateTime.Now.Year.ToString(), 8);
            }
            //drw["BUYER_DEL"] = false;
            //drw["BUYER_RATE_SID"] = "";

            return true;
        }
        public string GetNewTradingNo()
        {
            return "02" + msBsc.SvRef.ApplicationConst.Const.GeneratelongId().ToString();
        }

        protected override bool AfterRowAdded(DataRow drw)
        {
            UpdateAccountChargeAmt(drw);
            return true;
        }

        /// <summary>
        /// 记录修改前检验
        /// </summary>
        /// <param name="drw">当前记录</param>
        /// <returns>>校验合法，返回值为true,否则返回false</returns>
        /// <remarks>
        /// ID不允许修改,并把此修改操作记录到BSE_MODIFY_HISTORY表中
        /// </remarks>
        protected override bool BeforeRowModified(DataRow drw)
        {
            //ID不容许修改
            if (drw[this.KeyFieldName].ToString() != drw[this.KeyFieldName, DataRowVersion.Original].ToString())
            {
                Exception e = new Exception(this.TableName + "表的主键" + this.KeyFieldName + "字段不允许被修改");
                throw e;
            } 
                if (drw["TRADING_SID"].ToString() == "已支付" && drw["TRADING_SID", DataRowVersion.Original].ToString()=="待支付")
                {
                    drw["PAY_ARRIVE_DT"] = DateTime.Now; 
                }
            return true;
        }

        protected override bool AfterRowModified(DataRow drw)
        {
            if (drw["TRADING_SID"].ToString() != drw["TRADING_SID", DataRowVersion.Original].ToString())
            {
                if (drw["TRADING_SID"].ToString() == "已支付" && drw["TRADING_SID", DataRowVersion.Original].ToString() == "待支付" && getIsCompletePay(drw))
                { 
                    if (drw["TRADING_TYPE_CID"].ToString() == "购物")
                    {
                        UpdateOrderPaySatus(drw["TRADING_NO"].ToString());
                    } 
                    if (drw["TRADING_TYPE_CID"].ToString() == "购积分")
                    {
                        UpdateScoreSalseLogPayStatus(drw["TRADING_NO"].ToString());
                        AddChargeTradingForPromoShopByScoreSales(drw);
                    }
                    doSqlForPayAfter(drw);
                }
            }
            UpdateAccountChargeAmt(drw);
            return true;
        }

        /// <summary>
        /// 获取订单是否完成支付，判断拆分支付的情况
        /// </summary>
        /// <param name="drw"></param>
        /// <returns></returns>
        private bool getIsCompletePay(DataRow drw)
        {
            if (drw["IS_SPLIT"].ToString() != "True")
            {
                return drw["TRADING_SID"].ToString() != "待支付";
            }
            else
            {
                DataSet ds = this.DataObj.QueryBySQL("SELECT TRADING_AMT FROM SHP_CHARGE_TRADING_LOG A WHERE A.TRADING_SID='待支付' AND TRADING_NO = '" + drw["TRADING_NO"].ToString() + "'");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }

        private void doSqlForPayAfter(DataRow drw)
        {
            if (drw["TRADING_SID"].ToString() == "已支付" && drw["PAY_AFTER_SQL"].ToString() != string.Empty)
            {
                this.DataObj.ExecuteBySQL(drw["PAY_AFTER_SQL"].ToString());
            }

        }

        private void UpdateAccountChargeAmt(DataRow drw)
        {
            if (drw.RowState == DataRowState.Added && drw["TRADING_SID"].ToString() == "已支付" 
                || drw.RowState == DataRowState.Modified && drw["TRADING_SID"].ToString() != drw["TRADING_SID", DataRowVersion.Original].ToString())
            {
                if (drw["TRADING_SID"].ToString() == "已支付")
                {
                    //账户增加余额
                    if (drw["TRADING_TYPE_CID"].ToString() == "充值" || drw["TRADING_TYPE_CID"].ToString() == "销售" || drw["TRADING_TYPE_CID"].ToString() == "退款")
                    {
                        if (drw["USER_TYPE_CID"].ToString() == "1")
                        {
                            this.DataObj.ExecuteBySQL("UPDATE SHP_COMMERCIAL_TENANT_INFO SET CHARGE_AMT=CHARGE_AMT+" + drw["TRADING_AMT"].ToString() + " WHERE COMM_TENANT_ID='" + drw["ACCOUNT_NO"].ToString() + "'");
                        }
                        else
                        {
                            this.DataObj.ExecuteBySQL("UPDATE SHP_CUSTOMER_INFO SET CHARGE_AMT=CHARGE_AMT+" + drw["TRADING_AMT"].ToString() + " WHERE USER_NME='" + drw["ACCOUNT_NO"].ToString() + "'");
                        }
                        //if (drw["TRADING_TYPE_CID"].ToString() == "充值")
                        //{
                        //    //客户充值送优币
                        //    if (drw["USER_TYPE_CID"].ToString() == "2")
                        //    {
                        //        using (CBizShpUMoneyTradingLog oumoney = new CBizShpUMoneyTradingLog())
                        //        {
                        //            oumoney.AddTradingLogForChongZhi(drw["ACCOUNT_NO"].ToString(), decimal.ToInt32((decimal)drw["TRADING_AMT"]));
                        //        }
                        //    } 
                        //}
                    }
                    //账户减少余额
                    if (drw["CHARGE_SRC_CID"].ToString() == "商城帐户" && drw["PAY_DIR"].ToString() == "支出")//.PAY_DIR='支出'
                    {
                        decimal decUserAmt = 0M;
                        if (drw["USER_TYPE_CID"].ToString() == "1")
                        {
                            using (msBsc.AppLogic.DataAlc.CBizShpCommercialTenantInfo ouinfo = new AppLogic.DataAlc.CBizShpCommercialTenantInfo())
                            {
                                decUserAmt = ouinfo.GetShopChargeAmt(drw["ACCOUNT_NO"].ToString());
                            }
                        }
                        else
                        {
                            using (msBsc.AppLogic.DataAlc.CBizShpCustomerInfo ouinfo = new AppLogic.DataAlc.CBizShpCustomerInfo())
                            {
                                decUserAmt = ouinfo.GetUserChargeAmt(drw["ACCOUNT_NO"].ToString());
                            }
                        }
                        if ((decimal)drw["TRADING_AMT"] > decUserAmt)
                        {
                            throw new Exception("账户【" + drw["ACCOUNT_NO"].ToString() + "】剩余资金【" + decUserAmt.ToString() + "】小于本次支付金额【" + drw["TRADING_AMT"].ToString() + "】，操作失败！");
                        }

                        if (drw["USER_TYPE_CID"].ToString() == "1")
                        {

                            this.DataObj.ExecuteBySQL("UPDATE SHP_COMMERCIAL_TENANT_INFO SET CHARGE_AMT=CHARGE_AMT-" + drw["TRADING_AMT"].ToString() + " WHERE COMM_TENANT_ID='" + drw["ACCOUNT_NO"].ToString() + "'");
                        }
                        else
                        {
                            this.DataObj.ExecuteBySQL("UPDATE SHP_CUSTOMER_INFO SET CHARGE_AMT=CHARGE_AMT-" + drw["TRADING_AMT"].ToString() + " WHERE USER_NME='" + drw["ACCOUNT_NO"].ToString() + "'");
                        }
                    }
                }

            }
        }

        /// <summary>
        /// 积分销售记录更新状态为已支付
        /// </summary>
        /// <param name="strOrderNo"></param>
        public void UpdateScoreSalseLogPayStatus(string strOrderNo)
        {
            using (CBizShpScoreSalesLog objss = new CBizShpScoreSalesLog())
            {
                DataSet dstm = objss.SelectByTradingNo(strOrderNo);
                if (dstm.Tables[0].Rows.Count > 0)
                {
                    dstm.Tables[0].Rows[0]["TRADING_SID"] = "已支付";
                    objss.Update(dstm);
                }
            }
        }


        
        /// <summary>
        /// 更新购物订单状态为已支付
        /// </summary>
        /// <param name="strOrderNos"></param>
        public void UpdateOrderPaySatus(string strOrderNo)
        {
            DataSet dstm = this.DataObj.QueryBySQL(@"
    SELECT
    B.*
    ,SRC_ALIPAY_TRADING_NO=V1.ALIPAY_TRADING_NO
    FROM 
    (
    SELECT TRADING_NO,ALIPAY_TRADING_NO=MAX(ALIPAY_TRADING_NO),TRADING_AMT=SUM(TRADING_AMT) FROM SHP_CHARGE_TRADING_LOG WHERE TRADING_SID='已支付' AND TRADING_TYPE_CID='购物' AND TRADING_NO = '" + strOrderNo + @"'  GROUP BY TRADING_NO
    ) AS V1
    LEFT OUTER JOIN SHP_ORDER_FORM B ON V1.TRADING_NO=B.ORDER_FORM_NO
    WHERE B.ORDER_FORM_ID IS NOT NULL AND V1.TRADING_AMT=B.PAID_AMT AND B.TRADE_STATUS_TXT='等待买家付款'
    ");
            dstm.Tables[0].TableName = "SHP_ORDER_FORM";

            for (int i = 0; i < dstm.Tables[0].Rows.Count; i++)
            {
                dstm.Tables[0].Rows[i]["TRADE_STATUS_TXT"] = "买家已付款";
                dstm.Tables[0].Rows[i]["ALIPAY_TRADING_NO"] = dstm.Tables[0].Rows[i]["ALIPAY_TRADING_NO"];
            }
            using (CBizShpOrderForm objorder = new CBizShpOrderForm())
            {
                objorder.Update(dstm);
            }
        }

        public DataSet SelectByIds(string strIdS)
        {
            DataSet ds = this.DataObj.QueryBySQL("SELECT * FROM " + this.TableName + " WHERE  " + this.KeyFieldName + " IN  ('" + strIdS.Replace("'", "").Replace(",", "','") + "')");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        public DataSet SelectByAccountNo(string strAccountNo)
        {
            DataSet ds = this.DataObj.QueryBySQL("SELECT * FROM " + this.TableName + " WHERE ACCOUNT_NO='" + strAccountNo + "' ORDER BY INITIAL_DT ASC");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        public DataSet SelectForFinder(string strTRADING_NO, string strACCOUNT_NO, string strINITIAL_DT_S, string strINITIAL_DT_E, string strTRADING_TYPE_CID, string strTRADING_SID, string strCHARGE_SRC_CID)
        {
            DataSet ds = this.DataObj.QueryBySQL("SELECT A.*"
                + " ,ALIPAY_MAIL=CASE WHEN A.USER_TYPE_CID='1' THEN C.ALIPAY_MAIL ELSE B.ALIPAY_MAIL END "
                + " ,K.BANK_CDE "
                + " ,K.BANK_NME "
                + " ,BANK_ACCOUNT_NO=CASE WHEN A.USER_TYPE_CID='1' THEN C.BANK_ACCOUNT_NO ELSE B.BANK_ACCOUNT_NO END "
                + " ,BANK_ACCOUNT_NME=CASE WHEN A.USER_TYPE_CID='1' THEN C.BANK_ACCOUNT_NME ELSE B.BANK_ACCOUNT_NME END "
                + " FROM " + this.TableName + " A "
                + " LEFT OUTER JOIN SHP_CUSTOMER_INFO B ON A.USER_TYPE_CID<>'1' AND A.ACCOUNT_NO=B.USER_NME "
                + " LEFT OUTER JOIN SHP_COMMERCIAL_TENANT_INFO C ON A.USER_TYPE_CID='1' AND A.ACCOUNT_NO=C.COMM_TENANT_ID "
                + " LEFT OUTER JOIN BSE_BANK K ON A.USER_TYPE_CID='1' AND C.BANK_CDE=K.BANK_CDE OR A.USER_TYPE_CID<>'1' AND B.BANK_CDE=K.BANK_CDE "
                + " WHERE (1=1)"
                + (strTRADING_NO == string.Empty ? "" : " AND (A.TRADING_NO='" + strTRADING_NO + "')")
                + (strACCOUNT_NO == string.Empty ? "" : " AND (A.ACCOUNT_NO='" + strACCOUNT_NO + "')")
                + (strINITIAL_DT_S == string.Empty ? "" : " AND (A.DATEDIFF(DAY,INITIAL_DT,'" + strINITIAL_DT_S + "')<=0)")
                + (strINITIAL_DT_E == string.Empty ? "" : " AND (A.DATEDIFF(DAY,INITIAL_DT,'" + strINITIAL_DT_E + "')>=0)")
                + (strTRADING_TYPE_CID == string.Empty ? "" : " AND (A.TRADING_TYPE_CID='" + strTRADING_TYPE_CID + "')")
                + (strTRADING_SID == string.Empty ? "" : " AND (A.TRADING_SID='" + strTRADING_SID + "')")
                + (strCHARGE_SRC_CID == string.Empty ? "" : " AND (A.CHARGE_SRC_CID='" + strCHARGE_SRC_CID + "')")
                + "  ORDER BY A.INITIAL_DT ASC");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }


        /// <summary>
        /// 付款到商城
        /// </summary>
        /// <param name="drOrder"></param>
        public DataRow PayChargeToMall(string strOrderNo, decimal decUserPaidAmt, decimal decOnlinePaidAmt)
        {
            strOrderNo = strOrderNo.Replace("'", ""); 
            if (strOrderNo == string.Empty || decUserPaidAmt == 0M && decOnlinePaidAmt == 0M)
            {
                throw new Exception("当前没有找到需要付款的订单，请返回重新选择！");
            } 
            DataSet dsLog = this.DataObj.QueryBySQL("SELECT * FROM SHP_CHARGE_TRADING_LOG A WHERE A.TRADING_SID='待支付' AND A.PAY_DIR='支出' AND TRADING_NO IN ('" + strOrderNo.Replace(",", "','") + "')");
            dsLog.Tables[0].TableName = "SHP_CHARGE_TRADING_LOG";
            for (int i = dsLog.Tables[0].Rows.Count-1; i >=0; i--)
            {
                DataRow drtlog = dsLog.Tables[0].Rows[i];
                if (decUserPaidAmt > 0)
                {
                    decimal decUserAmt = 0M;
                    if (drtlog["USER_TYPE_CID"].ToString() == "1")
                    {
                        using (msBsc.AppLogic.DataAlc.CBizShpCommercialTenantInfo ouinfo = new AppLogic.DataAlc.CBizShpCommercialTenantInfo())
                        {
                            decUserAmt = ouinfo.GetShopChargeAmt(drtlog["ACCOUNT_NO"].ToString());
                        }
                    }
                    else
                    {
                        using (msBsc.AppLogic.DataAlc.CBizShpCustomerInfo ouinfo = new AppLogic.DataAlc.CBizShpCustomerInfo())
                        {
                            decUserAmt = ouinfo.GetUserChargeAmt(drtlog["ACCOUNT_NO"].ToString());
                        }
                    }
                    if (decUserPaidAmt > decUserAmt)
                    {
                        throw new Exception("当前账户金额过少，不能完成本次支付请求，请调整帐号支付金额后再继续提交付款请求！");
                    }
                    else
                    {
                        //增加账户支付的商城转账记录
                        if ((decimal)drtlog["TRADING_AMT"] <= decUserPaidAmt)//全部账户支付
                        {
                            drtlog["SUBMIT_PAY_DT"] = DateTime.Now;
                            drtlog["PAY_ARRIVE_DT"] = DateTime.Now;
                            drtlog["TRADING_SID"] = "已支付";
                            drtlog["CHARGE_SRC_CID"] = "商城帐户";
                            if (drtlog["TRADING_TYPE_CID"].ToString() == "")
                            {
                            }
                            decUserPaidAmt=decUserPaidAmt-(decimal)drtlog["TRADING_AMT"];
                        }
                        else//部分账户支付
                        {
                            DataRow drnewtrad2 = dsLog.Tables[0].NewRow();
                            drnewtrad2["CHARGE_TRADING_ID"] = this.DataObj.NewID();
                            drnewtrad2["ACCOUNT_NO"] = drtlog["ACCOUNT_NO"];
                            drnewtrad2["ACCOUNT_NME"] = drtlog["ACCOUNT_NME"];
                            drnewtrad2["USER_TYPE_CID"] = drtlog["USER_TYPE_CID"];
                            drnewtrad2["PAY_DIR"] = drtlog["PAY_DIR"];//收付：收入、支出
                            drnewtrad2["CHARGE_SRC_CID"] = "在线支付";//费用来源：商城帐户，在线支付,推广账户
                            drnewtrad2["TRADING_NO"] = drtlog["TRADING_NO"];
                            drnewtrad2["TRADING_NME"] = drtlog["TRADING_NME"];
                            drnewtrad2["TRADING_TYPE_CID"] = drtlog["TRADING_TYPE_CID"];//交易类型：购物，充值，缴费，提现，销售,购积分
                            drnewtrad2["OTH_ACCOUNT_NO"] = drtlog["OTH_ACCOUNT_NO"];
                            drnewtrad2["OTH_ACCOUNT_NME"] = drtlog["OTH_ACCOUNT_NME"];
                            drnewtrad2["TRADING_AMT"] = (decimal)drtlog["TRADING_AMT"] - decUserPaidAmt;
                            drnewtrad2["TRADING_SID"] = drtlog["TRADING_SID"];
                            drnewtrad2["TRADING_DESC"] = drtlog["TRADING_DESC"];
                            drnewtrad2["IS_SPLIT"] = true;
                            drnewtrad2["SUBMIT_PAY_DT"] = DateTime.Now;
                            drnewtrad2["PAY_ARRIVE_DT"] = DateTime.Now;
                            dsLog.Tables[0].Rows.Add(drnewtrad2);

                            drtlog["TRADING_AMT"] = decUserPaidAmt;
                            drtlog["TRADING_SID"] = "已支付";
                            drtlog["IS_SPLIT"] = true;
                            drtlog["CHARGE_SRC_CID"] = "商城帐户";

                            decUserPaidAmt = decUserPaidAmt - (decimal)drtlog["TRADING_AMT"];
                            decOnlinePaidAmt = decOnlinePaidAmt - (decimal)drnewtrad2["TRADING_AMT"];

                            if (i != 0)
                            {
                                throw new Exception("在线支付一次只能支付一个订单，请返回重新选择！");
                            }
                            else
                            {
                                if (decOnlinePaidAmt != 0)
                                {
                                    throw new Exception("在线支付的金额校验错误，请返回重新选择！");
                                }
                                this.Update(dsLog);
                                dsLog.AcceptChanges();
                                return drnewtrad2;
                            }
                        }

                        if (i == 0)
                        {
                            if (decUserPaidAmt > 0)
                            {
                                throw new Exception("账户支付的金额校验错误，请返回重新选择！");
                            }
                            else
                            {
                                this.Update(dsLog);
                                return null;
                            }
                        }
                    }

                }
                else
                {
                    if (i != 0)
                    {
                        throw new Exception("在线支付一次只能支付一个订单，请返回重新选择！");
                    }
                    else
                    {
                        decOnlinePaidAmt = decOnlinePaidAmt - (decimal)drtlog["TRADING_AMT"];
                        if (decOnlinePaidAmt != 0)
                        {
                            throw new Exception("在线支付的金额校验错误，请返回重新选择！");
                        }


                        drtlog["SUBMIT_PAY_DT"] = DateTime.Now;
                        this.Update(dsLog);
                        dsLog.AcceptChanges();
                        return drtlog;
                    }
                }
            }


            throw new Exception("当前没有找到需要付款的订单，请返回重新选择！");
             
        }

        /// <summary>
        /// 保存支付返回信息，返回OK
        /// </summary>
        /// <param name="trade_no"></param>
        /// <param name="order_no"></param>
        /// <param name="total_fee"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="buyer_email"></param>
        /// <param name="trade_status"></param>
        /// <param name="refund_status"></param>
        /// <returns></returns>
        public string doSaveAlipay(string trade_no, string order_no, string total_fee, string subject, string body, string buyer_email, string trade_status, string refund_status)
        {
            DataSet dsLog = this.DataObj.QueryBySQL("SELECT * FROM SHP_CHARGE_TRADING_LOG A WHERE A.TRADING_SID='待支付' AND A.PAY_DIR='支出' AND TRADING_NO ='" + order_no + "'");
            dsLog.Tables[0].TableName = "SHP_CHARGE_TRADING_LOG";
            string strErrmsg = "";
            string strTradingId = "";
            bool blPayed = false;
            bool blNeedLog = false;
            decimal decAmt = 0;
            if (dsLog.Tables[0].Rows.Count > 0)
            {
                strTradingId = dsLog.Tables[0].Rows[0]["CHARGE_TRADING_ID"].ToString();
                //if (decimal.TryParse(total_fee, out decAmt))
                //{
                //    decAmt = decimal.Parse(total_fee);
                //}
                //else
                //{
                //    strErrmsg += "返回支付金额参数错误!";
                //}
                //if ((decimal)dsLog.Tables[0].Rows[0]["TRADING_AMT"] != decAmt)
                //{
                //    strErrmsg += "返回支付金额不等于待支付金额!";
                //}
                if (strErrmsg == string.Empty)
                {
                    blPayed = true;
                    blNeedLog = true;
                    dsLog.Tables[0].Rows[0]["ALIPAY_TRADING_NO"] = trade_no;
                    dsLog.Tables[0].Rows[0]["TRADING_SID"] = "已支付";
                    this.Update(dsLog);
                }
                else if (dsLog.Tables[0].Rows[0]["TRADING_DESC"].ToString().IndexOf(strErrmsg) == -1)
                {
                    blNeedLog = true;
                    dsLog.Tables[0].Rows[0]["TRADING_DESC"] = strErrmsg;
                    this.Update(dsLog);
                }

            }
            else
            {
                return "OK";
            }

            if (blNeedLog)
            {
                using (CBizShpChargeAlipayLog objalpay = new CBizShpChargeAlipayLog())
                {
                    DataSet dsAlilog;
                    //if (!blPayed)
                    //{
                    //    dsAlilog = objalpay.SelectByAlipayNo(trade_no);
                    //}
                    //else
                    //{
                    dsAlilog = new CDmShpChargeAlipayLog();
                    //}

                    DataRow drnew = dsAlilog.Tables[0].NewRow();
                    drnew["ALIPAY_LOG_ID"] = this.DataObj.NewID();
                    drnew["CHARGE_TRADING_ID"] = strTradingId;
                    drnew["ALIPAY_TRADING_NO"] = trade_no;
                    drnew["OUT_TRADING_NO"] = order_no;
                    drnew["TRADING_AMT"] = decAmt;
                    drnew["TRADING_NME"] = subject;
                    drnew["TRADING_DESC"] =strErrmsg+ body;
                    drnew["BUYER_EMAIL"] = buyer_email;
                    drnew["TRADING_STATUS"] = trade_status;
                    drnew["REFUND_STATUS"] = refund_status;
                    dsAlilog.Tables[0].Rows.Add(drnew);
                    objalpay.Update(dsAlilog);
                }
            }
            if(strErrmsg==string.Empty)
            {
                strErrmsg = "OK";
            }
            return strErrmsg;
        }

        /// <summary>
        /// 在线充值
        /// </summary>
        /// <param name="strChongzhiAMt"></param>
        /// <returns></returns>
        public DataRow AddTradingLogForChongzhi(string strChongzhiAMt, string strAccNo, string strAccNme, string strAccType)
        {
            decimal decAmt = 0;
            if (decimal.TryParse(strChongzhiAMt, out decAmt))
            {
                decAmt = decimal.Parse(strChongzhiAMt);
            }
            else
            {
                throw new Exception("请输入正确的金额！");
            }


            if (decAmt <= 0)
            {
                throw new Exception("请输入正确的金额！");
            }


            DataSet dstrad = new CDmShpChargeTradingLog();
             
            DataRow drnewtrad2 = dstrad.Tables[0].NewRow();
            drnewtrad2["CHARGE_TRADING_ID"] = this.DataObj.NewID();

            drnewtrad2["ACCOUNT_NO"] = strAccNo;
            drnewtrad2["ACCOUNT_NME"] = strAccNme;
            drnewtrad2["USER_TYPE_CID"] = strAccType;


            //if (msBsc.SvRef.ApplicationConst.Const.OperType == "1")
            //{
            //    drnewtrad2["ACCOUNT_NO"] = msBsc.SvRef.ApplicationConst.Const.OperDealerId.Split(',')[0];
            //    drnewtrad2["ACCOUNT_NME"] = msBsc.SvRef.ApplicationConst.Const.OperDealerId.Split(',')[1];
            //}
            //else
            //{
            //    drnewtrad2["ACCOUNT_NO"] = msBsc.SvRef.UserInfo.Operator;
            //    drnewtrad2["ACCOUNT_NME"] = msBsc.SvRef.UserInfo.Operator;
            //}
            //drnewtrad2["USER_TYPE_CID"] = msBsc.SvRef.ApplicationConst.Const.OperType;
            drnewtrad2["PAY_DIR"] = "支出";//收付：收入、支出
            drnewtrad2["CHARGE_SRC_CID"] = "在线支付";//费用来源：商城帐户，在线支付,推广账户
            drnewtrad2["TRADING_NO"] = GetNewTradingNo();// msBsc.SvRef.ApplicationConst.Const.GeneratelongId().ToString();
            drnewtrad2["TRADING_NME"] = "充值到地接客商城";
            drnewtrad2["TRADING_TYPE_CID"] = "充值";//交易类型：购物，充值，缴费，提现，销售,购积分
            drnewtrad2["OTH_ACCOUNT_NO"] = "system";
            drnewtrad2["OTH_ACCOUNT_NME"] = "地接客商城";
            drnewtrad2["TRADING_AMT"] = decAmt;
            drnewtrad2["TRADING_SID"] = "待支付";
            drnewtrad2["TRADING_DESC"] = "";
            dstrad.Tables[0].Rows.Add(drnewtrad2);
             
            this.Update(dstrad);

            return drnewtrad2;
            //}
        }


        /// <summary>
        /// 缴费，如缴纳保证金等
        /// </summary>
        /// <param name="strJiaofeiAMt"></param>
        /// <param name="strAccNo"></param>
        /// <param name="strAccNme"></param>
        /// <param name="strAccType"></param>
        /// <param name="strChargeDesc"></param>
        /// <returns></returns>
        public DataRow AddTradingLogForJiaofei(string strJiaofeiAMt, string strAccNo, string strAccNme, string strAccType,string strChargeDesc,string strPayAfterSql)
        {
            decimal decAmt = 0;
            if (decimal.TryParse(strJiaofeiAMt, out decAmt))
            {
                decAmt = decimal.Parse(strJiaofeiAMt);
            }
            else
            {
                throw new Exception("请输入正确的金额！");
            }


            if (decAmt <= 0)
            {
                throw new Exception("请输入正确的金额！");
            }
            if (strChargeDesc == string.Empty)
            {
                strChargeDesc = "缴费到地接客商城";
            }

            DataSet dstrad = new CDmShpChargeTradingLog();
             
            DataRow drnewtrad2 = dstrad.Tables[0].NewRow();
            drnewtrad2["CHARGE_TRADING_ID"] = this.DataObj.NewID();

            drnewtrad2["ACCOUNT_NO"] = strAccNo;
            drnewtrad2["ACCOUNT_NME"] = strAccNme;
            drnewtrad2["USER_TYPE_CID"] = strAccType;


            //if (msBsc.SvRef.ApplicationConst.Const.OperType == "1")
            //{
            //    drnewtrad2["ACCOUNT_NO"] = msBsc.SvRef.ApplicationConst.Const.OperDealerId.Split(',')[0];
            //    drnewtrad2["ACCOUNT_NME"] = msBsc.SvRef.ApplicationConst.Const.OperDealerId.Split(',')[1];
            //}
            //else
            //{
            //    drnewtrad2["ACCOUNT_NO"] = msBsc.SvRef.UserInfo.Operator;
            //    drnewtrad2["ACCOUNT_NME"] = msBsc.SvRef.UserInfo.Operator;
            //}
            //drnewtrad2["USER_TYPE_CID"] = msBsc.SvRef.ApplicationConst.Const.OperType;
            drnewtrad2["PAY_DIR"] = "支出";//收付：收入、支出
            drnewtrad2["CHARGE_SRC_CID"] = "在线支付";//费用来源：商城帐户，在线支付,推广账户
            drnewtrad2["TRADING_NO"] = GetNewTradingNo();// msBsc.SvRef.ApplicationConst.Const.GeneratelongId().ToString();
            drnewtrad2["TRADING_NME"] = strChargeDesc;
            drnewtrad2["TRADING_TYPE_CID"] = "缴费";//交易类型：购物，充值，缴费，提现，销售,购积分
            drnewtrad2["OTH_ACCOUNT_NO"] = "system";
            drnewtrad2["OTH_ACCOUNT_NME"] = "地接客商城";
            drnewtrad2["TRADING_AMT"] = decAmt;
            drnewtrad2["TRADING_SID"] = "待支付";
            drnewtrad2["TRADING_DESC"] = "";
            drnewtrad2["PAY_AFTER_SQL"] = strPayAfterSql;
            dstrad.Tables[0].Rows.Add(drnewtrad2);
             
            this.Update(dstrad);

            return drnewtrad2;
            //}
        }


        /// <summary>
        /// 提现
        /// </summary>
        /// <param name="strChongzhiAMt"></param>
        /// <returns></returns>
        public DataRow AddTradingLogForGetCash(string strChongzhiAMt, string strAccNo, string strAccNme, string strAccType)
        {
            decimal decAmt = 0;
            if (decimal.TryParse(strChongzhiAMt, out decAmt))
            {
                decAmt = decimal.Parse(strChongzhiAMt);
            }
            else
            {
                throw new Exception("请输入正确的金额！");
            }


            if (decAmt <= 0)
            {
                throw new Exception("请输入正确的金额！");
            }
            decimal decUserAmt = 0M;
            if (strAccType == "1")
            {
                using (msBsc.AppLogic.DataAlc.CBizShpCommercialTenantInfo ouinfo = new AppLogic.DataAlc.CBizShpCommercialTenantInfo())
                {
                    decUserAmt = ouinfo.GetShopChargeAmt(strAccNo);
                }
            }
            else
            {
                using (msBsc.AppLogic.DataAlc.CBizShpCustomerInfo ouinfo = new AppLogic.DataAlc.CBizShpCustomerInfo())
                {
                    decUserAmt = ouinfo.GetUserChargeAmt(strAccNo);
                }
            }

            if (decAmt > decUserAmt)
            {
                throw new Exception("提现金额已超出账户金额，请输入正确的金额！");
            }


            DataSet dstrad = new CDmShpChargeTradingLog();
             
            DataRow drnewtrad2 = dstrad.Tables[0].NewRow();
            drnewtrad2["CHARGE_TRADING_ID"] = this.DataObj.NewID();
            //if (msBsc.SvRef.ApplicationConst.Const.OperType == "1")
            //{
            //    drnewtrad2["ACCOUNT_NO"] = msBsc.SvRef.ApplicationConst.Const.OperDealerId.Split(',')[0];
            //    drnewtrad2["ACCOUNT_NME"] = msBsc.SvRef.ApplicationConst.Const.OperDealerId.Split(',')[1];
            //}
            //else
            //{
            //    drnewtrad2["ACCOUNT_NO"] = msBsc.SvRef.UserInfo.Operator;
            //    drnewtrad2["ACCOUNT_NME"] = msBsc.SvRef.UserInfo.Operator;
            //}
            //drnewtrad2["USER_TYPE_CID"] = msBsc.SvRef.ApplicationConst.Const.OperType;


            drnewtrad2["ACCOUNT_NO"] = strAccNo;
            drnewtrad2["ACCOUNT_NME"] = strAccNme;
            drnewtrad2["USER_TYPE_CID"] = strAccType;



            drnewtrad2["PAY_DIR"] = "支出";//收付：收入、支出
            drnewtrad2["CHARGE_SRC_CID"] = "商城帐户";//费用来源：商城帐户，在线支付,推广账户
            drnewtrad2["TRADING_NO"] = GetNewTradingNo();// msBsc.SvRef.ApplicationConst.Const.GeneratelongId().ToString();
            drnewtrad2["TRADING_NME"] = "从商城账户提现";
            drnewtrad2["TRADING_TYPE_CID"] = "提现";//交易类型：购物，充值，缴费，提现，销售,购积分
            drnewtrad2["OTH_ACCOUNT_NO"] = "system";
            drnewtrad2["OTH_ACCOUNT_NME"] = "地接客商城";
            drnewtrad2["TRADING_AMT"] = decAmt;
            drnewtrad2["TRADING_SID"] = "待支付";
            drnewtrad2["TRADING_DESC"] = "";
            dstrad.Tables[0].Rows.Add(drnewtrad2);
             
            this.Update(dstrad);

            return drnewtrad2;
            //}
        }

        /// <summary>
        /// 生成付款账单，费用来源：商城帐户，在线支付 ,推广账户
        /// </summary>
        /// <param name="drOrder"></param>
        public void AddTradingLogForAddOrder(DataRow drOrder)
        {
            if ((decimal)drOrder["PAID_AMT"] <= 0)
            {
                return;
            } 
            DataSet dstrad = new CDmShpChargeTradingLog();

            //客户增加积分
            DataRow drnewtrad2 = dstrad.Tables[0].NewRow();
            drnewtrad2["CHARGE_TRADING_ID"] = this.DataObj.NewID();
            drnewtrad2["ACCOUNT_NO"] = drOrder["USER_NME"];
            drnewtrad2["ACCOUNT_NME"] = drOrder["USER_NME"];
            drnewtrad2["USER_TYPE_CID"] = "2";
            drnewtrad2["PAY_DIR"] = "支出";//收付：收入、支出
            drnewtrad2["CHARGE_SRC_CID"] = "在线支付";//费用来源：商城帐户，在线支付,推广账户
            drnewtrad2["TRADING_NO"] = drOrder["ORDER_FORM_NO"];
            drnewtrad2["TRADING_NME"] = drOrder["ORDER_FORM_NME"];
            drnewtrad2["TRADING_TYPE_CID"] = "购物";//交易类型：购物，充值，缴费，提现，销售,购积分
            drnewtrad2["OTH_ACCOUNT_NO"] = "system";
            drnewtrad2["OTH_ACCOUNT_NME"] = "地接客商城";
            drnewtrad2["TRADING_AMT"] =  drOrder["PAID_AMT"] ;
            drnewtrad2["TRADING_SID"] = "待支付"; 
            drnewtrad2["TRADING_DESC"] = "";
            dstrad.Tables[0].Rows.Add(drnewtrad2);

            //this.DataObj.ExecuteBySQL("UPDATE A SET SCORE_QTY=ISNULL(A.SCORE_QTY,0)-" + drOrder["PAID_SCORE_QTY"].ToString() + " FROM SHP_CUSTOMER_INFO A WHERE A.USER_NME='" + drOrder["USER_NME"].ToString() + "'");
            //this.DataObj.ExecuteBySQL("UPDATE A SET SCORE_QTY=ISNULL(A.SCORE_QTY,0)+" + drOrder["PAID_SCORE_QTY"].ToString() + " FROM SHP_COMMERCIAL_TENANT_INFO A WHERE A.COMM_TENANT_ID='" + drOrder["COMM_TENANT_ID"].ToString() + "'");
            //}

            this.Update(dstrad);

            //}
        }

        /// <summary>
        /// 增加积分销售付款记录
        /// </summary>
        /// <param name="drOrder"></param>
        public void AddTradingLogForAddScoreSalse(DataRow drOrder)
        {
            if ((decimal)drOrder["STL_AMT"] <= 0)
            {
                return;
            }
            DataSet dstrad = new CDmShpChargeTradingLog();

            //客户增加积分
            DataRow drnewtrad2 = dstrad.Tables[0].NewRow();
            drnewtrad2["CHARGE_TRADING_ID"] = this.DataObj.NewID();
            drnewtrad2["ACCOUNT_NO"] = drOrder["COMM_TENANT_ID"];
            drnewtrad2["ACCOUNT_NME"] = drOrder["COMM_TENANT_NME"];
            drnewtrad2["USER_TYPE_CID"] = "1";
            drnewtrad2["PAY_DIR"] = "支出";//收付：收入、支出
            drnewtrad2["CHARGE_SRC_CID"] = "在线支付";//费用来源：商城帐户，在线支付,推广账户
            drnewtrad2["TRADING_NO"] = drOrder["TRADING_NO"]; 
            drnewtrad2["TRADING_NME"] = "购买积分";
            drnewtrad2["TRADING_TYPE_CID"] = "购积分";//交易类型：购物，充值，缴费，提现，销售,购积分
            drnewtrad2["OTH_ACCOUNT_NO"] = "system";
            drnewtrad2["OTH_ACCOUNT_NME"] = "地接客商城";
            drnewtrad2["TRADING_AMT"] =  drOrder["STL_AMT"];
            drnewtrad2["TRADING_SID"] = "待支付";
            drnewtrad2["TRADING_DESC"] = "向地接客商城购买积分";
            dstrad.Tables[0].Rows.Add(drnewtrad2);

            //this.DataObj.ExecuteBySQL("UPDATE A SET SCORE_QTY=ISNULL(A.SCORE_QTY,0)-" + drOrder["PAID_SCORE_QTY"].ToString() + " FROM SHP_CUSTOMER_INFO A WHERE A.USER_NME='" + drOrder["USER_NME"].ToString() + "'");
            //this.DataObj.ExecuteBySQL("UPDATE A SET SCORE_QTY=ISNULL(A.SCORE_QTY,0)+" + drOrder["PAID_SCORE_QTY"].ToString() + " FROM SHP_COMMERCIAL_TENANT_INFO A WHERE A.COMM_TENANT_ID='" + drOrder["COMM_TENANT_ID"].ToString() + "'");
            //}

            this.Update(dstrad);

            //}
        }

        public DataSet SelectByTradingNo(string strTradingNo,string strTradingType)
        {
            DataSet ds = this.DataObj.QueryBySQL("SELECT * FROM " + this.TableName + " WHERE TRADING_NO='" + strTradingNo + "' AND TRADING_TYPE_CID='" + strTradingType + "' ORDER BY INITIAL_DT ASC");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        //未签收前退款
        public void AddTradingLogForOrderReturn(DataRow drOrder)
        {
            if ((decimal)drOrder["PAID_AMT"] <= 0)
            {
                return;
            }

            DataSet dstm = this.SelectByTradingNo(drOrder["ORDER_FORM_NO"].ToString(), "购物");

            //待支付时取消支付
            //已支付时生成退款账单
            for (int i = dstm.Tables[0].Rows.Count - 1; i >= 0; i--)
            {
                DataRow drtlog = dstm.Tables[0].Rows[i];
                if (dstm.Tables[0].Rows[i]["TRADING_SID"].ToString() == "待支付")
                {
                    dstm.Tables[0].Rows[i]["TRADING_SID"] = "已取消";
                }
                if (dstm.Tables[0].Rows[i]["TRADING_SID"].ToString() == "已支付")
                {
                    //dstm.Tables[0].Rows[i]["TRADING_SID"] = "已取消";
                    //DataSet dstrad = new CDmShpChargeTradingLog();
                     
                    DataRow drnewtrad2 = dstm.Tables[0].NewRow();
                    drnewtrad2["CHARGE_TRADING_ID"] = this.DataObj.NewID();
                    drnewtrad2["ACCOUNT_NO"] = drtlog["ACCOUNT_NO"];
                    drnewtrad2["ACCOUNT_NME"] = drtlog["ACCOUNT_NME"];
                    drnewtrad2["USER_TYPE_CID"] = drtlog["USER_TYPE_CID"];
                    drnewtrad2["PAY_DIR"] = "收入";//收付：收入、支出
                    drnewtrad2["CHARGE_SRC_CID"] = "商城帐户";//费用来源：商城帐户，在线支付，推广账户
                    drnewtrad2["TRADING_NO"] = drtlog["TRADING_NO"];
                    drnewtrad2["TRADING_NME"] = drtlog["TRADING_NME"];
                    drnewtrad2["TRADING_TYPE_CID"] = "退款";//交易类型：购物，充值，缴费，提现，销售,购积分
                    drnewtrad2["OTH_ACCOUNT_NO"] = "system";
                    drnewtrad2["OTH_ACCOUNT_NME"] = "地接客商城";
                    drnewtrad2["TRADING_AMT"] = drtlog["TRADING_AMT"];
                    drnewtrad2["TRADING_SID"] = "已支付";
                    drnewtrad2["TRADING_DESC"] = "购物退款到账户余额";
                    drnewtrad2["SUBMIT_PAY_DT"] = DateTime.Now;
                    drnewtrad2["PAY_ARRIVE_DT"] = DateTime.Now;


                    dstm.Tables[0].Rows.Add(drnewtrad2);


                }
            }
            if (dstm.HasChanges())
            {
                this.Update(dstm);
            }

            //}
        }

        /// <summary>
        /// 完成交易后转账给商家
        /// </summary>
        /// <param name="drOrder"></param>
        public void AddTradingLogForOrderCmp(DataRow drOrder)
        {
            if ((decimal)drOrder["PAID_AMT"] <= 0)
            {
                return;
            }

            DataSet dstm = this.SelectByTradingNo(drOrder["ORDER_FORM_NO"].ToString(), "购物");

            //校验买家付款金额
            decimal decLedgerAmt = 0M;
            for (int i = dstm.Tables[0].Rows.Count - 1; i >= 0; i--)
            {
                DataRow drtlog = dstm.Tables[0].Rows[i];
                if (dstm.Tables[0].Rows[i]["TRADING_SID"].ToString() == "待支付" || dstm.Tables[0].Rows[i]["TRADING_SID"].ToString() == "已取消")
                {
                    throw new Exception("买家未完成付款，不能完成转账到商家的交易！");
                }
                if (dstm.Tables[0].Rows[i]["TRADING_SID"].ToString() == "已支付")
                {
                    decLedgerAmt += (decimal)dstm.Tables[0].Rows[i]["TRADING_AMT"];
                }
            }
            if ((decimal)drOrder["PAID_AMT"] != decLedgerAmt)
            {
                throw new Exception("应支付金额和实际账单金额有差异，不能完成操作！");
            }

            //转账给商家
            DataRow drnewtrad = dstm.Tables[0].NewRow();
            drnewtrad["CHARGE_TRADING_ID"] = this.DataObj.NewID();
            drnewtrad["ACCOUNT_NO"] = drOrder["COMM_TENANT_ID"];
            drnewtrad["ACCOUNT_NME"] = drOrder["COMM_TENANT_NME"];
            drnewtrad["USER_TYPE_CID"] = "1";
            drnewtrad["PAY_DIR"] = "收入";//收付：收入、支出
            drnewtrad["CHARGE_SRC_CID"] = "商城帐户";//费用来源：商城帐户，在线支付，推广账户
            drnewtrad["TRADING_NO"] = drOrder["ORDER_FORM_NO"];
            drnewtrad["TRADING_NME"] = drOrder["ORDER_FORM_NME"];
            drnewtrad["TRADING_TYPE_CID"] = "销售";//交易类型：购物，充值，缴费，提现，销售,购积分,扣点
            drnewtrad["OTH_ACCOUNT_NO"] = "system";
            drnewtrad["OTH_ACCOUNT_NME"] = "地接客商城";
            drnewtrad["TRADING_AMT"] = drOrder["PAID_AMT"];
            drnewtrad["TRADING_SID"] = "已支付";
            drnewtrad["TRADING_DESC"] = "出售商品收款";
            dstm.Tables[0].Rows.Add(drnewtrad);
            if (dstm.HasChanges())
            {
                this.Update(dstm);
                dstm.AcceptChanges();
            }

            //取所有商品中的最高服务费率
            DataSet dstm2 = this.DataObj.QueryBySQL(@"
    SELECT TOP 1
    MALL_SVC_RATE=CASE WHEN ISNULL(C3.MALL_SVC_RATE,0)<>0 THEN C3.MALL_SVC_RATE ELSE 
					    (CASE WHEN ISNULL(C2.MALL_SVC_RATE,0)<>0 THEN C2.MALL_SVC_RATE ELSE ISNULL(C1.MALL_SVC_RATE,0) END)
			      END
    FROM SHP_ORDER_FORM A 
    LEFT OUTER JOIN SHP_ORDER_FORM_LIST B ON A.ORDER_FORM_ID=B.ORDER_FORM_ID 
    LEFT OUTER JOIN SHP_GOODS_INFO C ON B.GOODS_ID=C.GOODS_ID
    LEFT OUTER JOIN SHP_GOODS_TYPE_LEVEL_ONE C1  ON C.LEVEL_ONE_ID=C1.LEVEL_ONE_ID
    LEFT OUTER JOIN SHP_GOODS_TYPE_LEVEL_TWO C2  ON C.LEVEL_TWO_ID=C2.LEVEL_TWO_ID
    LEFT OUTER JOIN SHP_GOODS_TYPE_LEVEL_THREE C3  ON C.LEVEL_THREE_ID=C3.LEVEL_THREE_ID
    WHERE 
    A.ORDER_FORM_NO='" + drOrder["ORDER_FORM_NO"].ToString() + @"'
    ORDER BY
    (CASE WHEN ISNULL(C3.MALL_SVC_RATE,0)<>0 THEN C3.MALL_SVC_RATE ELSE 
					    (CASE WHEN ISNULL(C2.MALL_SVC_RATE,0)<>0 THEN C2.MALL_SVC_RATE ELSE ISNULL(C1.MALL_SVC_RATE,0) END)
			      END) DESC
    ");

            if (dstm2.Tables[0].Rows.Count > 0 && (decimal)dstm2.Tables[0].Rows[0]["MALL_SVC_RATE"] !=0M)
            { 
                //扣点到商城
                DataRow drnewtrad2 = dstm.Tables[0].NewRow();
                drnewtrad2["CHARGE_TRADING_ID"] = this.DataObj.NewID();
                drnewtrad2["ACCOUNT_NO"] = drOrder["COMM_TENANT_ID"];
                drnewtrad2["ACCOUNT_NME"] = drOrder["COMM_TENANT_NME"];
                drnewtrad2["USER_TYPE_CID"] = "1";
                drnewtrad2["PAY_DIR"] = "支出";//收付：收入、支出
                drnewtrad2["CHARGE_SRC_CID"] = "商城帐户";//费用来源：商城帐户，在线支付，推广账户
                drnewtrad2["TRADING_NO"] = drOrder["ORDER_FORM_NO"];
                drnewtrad2["TRADING_NME"] = drOrder["ORDER_FORM_NME"];
                drnewtrad2["TRADING_TYPE_CID"] = "扣点";//交易类型：购物，充值，缴费，提现，销售,购积分,扣点
                drnewtrad2["OTH_ACCOUNT_NO"] = "system";
                drnewtrad2["OTH_ACCOUNT_NME"] = "地接客商城";
                drnewtrad2["TRADING_AMT"] =  (decimal)drOrder["PAID_AMT"] * (decimal)dstm2.Tables[0].Rows[0]["MALL_SVC_RATE"];
                drnewtrad2["TRADING_SID"] = "已支付";
                drnewtrad2["TRADING_DESC"] = "出售商品扣点到商城（标准" + dstm2.Tables[0].Rows[0]["MALL_SVC_RATE"].ToString() + "）";
                dstm.Tables[0].Rows.Add(drnewtrad2);



                //商家推广分成

                DataSet dstm6 = this.DataObj.QueryBySQL("SELECT B.FWDUSER_NME,A.PROMOTION_NME FROM SHP_COMMERCIAL_TENANT_INFO S LEFT OUTER JOIN  SYS_USER A ON S.USER_NME=A.USER_NME LEFT OUTER JOIN SYS_USER B ON A.PROMOTION_NME IS NOT NULL AND A.PROMOTION_NME<>'' AND A.PROMOTION_NME=B.USER_NME WHERE A.PROMOTION_NME IS NOT NULL AND A.PROMOTION_NME<>'' AND S.COMM_TENANT_ID='" + drOrder["COMM_TENANT_ID"].ToString() + "'");
                if (dstm6.Tables[0].Rows.Count > 0)
                { 
                    DataRow drnewtrad3 = dstm.Tables[0].NewRow();
                    drnewtrad3["CHARGE_TRADING_ID"] = this.DataObj.NewID();
                    drnewtrad3["ACCOUNT_NO"] = dstm6.Tables[0].Rows[0]["PROMOTION_NME"].ToString();
                    drnewtrad3["ACCOUNT_NME"] = dstm6.Tables[0].Rows[0]["PROMOTION_NME"].ToString();
                    drnewtrad3["USER_TYPE_CID"] = "3";
                    drnewtrad3["PAY_DIR"] = "收入";//收付：收入、支出
                    drnewtrad3["CHARGE_SRC_CID"] = "商城帐户";//费用来源：商城帐户，在线支付，推广账户
                    drnewtrad3["TRADING_NO"] = drOrder["ORDER_FORM_NO"];
                    drnewtrad3["TRADING_NME"] = drOrder["ORDER_FORM_NME"];
                    drnewtrad3["TRADING_TYPE_CID"] = "扣点";//交易类型：购物，充值，缴费，提现，销售,购积分,扣点
                    drnewtrad3["OTH_ACCOUNT_NO"] = "system";
                    drnewtrad3["OTH_ACCOUNT_NME"] = "地接客商城";
                    drnewtrad3["TRADING_AMT"] = ((decimal)drnewtrad2["TRADING_AMT"] * msBsc.AppLogic.Cfg.SystemSet.oSystemSet.getSysSetVal<decimal>("_SHOP_PROMO_SVC_AMT_PER")) / 2;
                    drnewtrad3["TRADING_SID"] = "已支付";
                    drnewtrad3["TRADING_DESC"] = "扣点分成给推广商（扣点标准" + dstm6.Tables[0].Rows[0]["MALL_SVC_RATE"].ToString() + "，分成标准" + msBsc.AppLogic.Cfg.SystemSet.oSystemSet.getSysSetVal<string>("_SHOP_PROMO_SVC_AMT_PER") + "）";
                    dstm.Tables[0].Rows.Add(drnewtrad3);


                    DataRow drnewtrad4 = dstm.Tables[0].NewRow();
                    drnewtrad4["CHARGE_TRADING_ID"] = this.DataObj.NewID();
                    drnewtrad4["ACCOUNT_NO"] = dstm6.Tables[0].Rows[0]["FWDUSER_NME"].ToString();
                    drnewtrad4["ACCOUNT_NME"] = dstm6.Tables[0].Rows[0]["FWDUSER_NME"].ToString();
                    drnewtrad4["USER_TYPE_CID"] = "4";
                    drnewtrad4["PAY_DIR"] = "收入";//收付：收入、支出
                    drnewtrad4["CHARGE_SRC_CID"] = "商城帐户";//费用来源：商城帐户，在线支付，推广账户
                    drnewtrad4["TRADING_NO"] = drOrder["ORDER_FORM_NO"];
                    drnewtrad4["TRADING_NME"] = drOrder["ORDER_FORM_NME"];
                    drnewtrad4["TRADING_TYPE_CID"] = "扣点";//交易类型：购物，充值，缴费，提现，销售,购积分,扣点
                    drnewtrad4["OTH_ACCOUNT_NO"] = "system";
                    drnewtrad4["OTH_ACCOUNT_NME"] = "地接客商城";
                    drnewtrad4["TRADING_AMT"] = ((decimal)drnewtrad2["TRADING_AMT"] * msBsc.AppLogic.Cfg.SystemSet.oSystemSet.getSysSetVal<decimal>("_SHOP_PROMO_SVC_AMT_PER")) / 2;
                    drnewtrad4["TRADING_SID"] = "已支付";
                    drnewtrad4["TRADING_DESC"] = "扣点分成给代理商（扣点标准" + dstm6.Tables[0].Rows[0]["MALL_SVC_RATE"].ToString() + "，分成标准" + msBsc.AppLogic.Cfg.SystemSet.oSystemSet.getSysSetVal<string>("_SHOP_PROMO_SVC_AMT_PER") + "）";
                    dstm.Tables[0].Rows.Add(drnewtrad4);
                     
                }
            }
            if (dstm.HasChanges())
            {
                this.Update(dstm);
            }

            //}
        }

        /// <summary>
        /// 积分销售推广分成
        /// </summary>
        /// <param name="drw"></param>
        public void AddChargeTradingForPromoShopByScoreSales(DataRow drw)
        { 
            //商家推广分成
            DataSet dstm = new CDmShpChargeTradingLog();
            DataSet dstm6 = this.DataObj.QueryBySQL("SELECT B.FWDUSER_NME,A.PROMOTION_NME FROM SHP_COMMERCIAL_TENANT_INFO S LEFT OUTER JOIN  SYS_USER A ON S.USER_NME=A.USER_NME LEFT OUTER JOIN SYS_USER B ON A.PROMOTION_NME IS NOT NULL AND A.PROMOTION_NME<>'' AND A.PROMOTION_NME=B.USER_NME WHERE A.PROMOTION_NME IS NOT NULL AND A.PROMOTION_NME<>'' AND S.COMM_TENANT_ID='" + drw["ACCOUNT_NO"].ToString() + "'");
            if (dstm6.Tables[0].Rows.Count > 0)
            {
                DataRow drnewtrad3 = dstm.Tables[0].NewRow();
                drnewtrad3["CHARGE_TRADING_ID"] = this.DataObj.NewID();
                drnewtrad3["ACCOUNT_NO"] = dstm6.Tables[0].Rows[0]["PROMOTION_NME"].ToString();
                drnewtrad3["ACCOUNT_NME"] = dstm6.Tables[0].Rows[0]["PROMOTION_NME"].ToString();
                drnewtrad3["USER_TYPE_CID"] = "3";
                drnewtrad3["PAY_DIR"] = "收入";//收付：收入、支出
                drnewtrad3["CHARGE_SRC_CID"] = "商城帐户";//费用来源：商城帐户，在线支付，推广账户
                drnewtrad3["TRADING_NO"] = drw["TRADING_NO"];
                drnewtrad3["TRADING_NME"] = drw["TRADING_NME"];
                drnewtrad3["TRADING_TYPE_CID"] = "购积分";//交易类型：购物，充值，缴费，提现，销售,购积分,扣点
                drnewtrad3["OTH_ACCOUNT_NO"] = "system";
                drnewtrad3["OTH_ACCOUNT_NME"] = "地接客商城";
                drnewtrad3["TRADING_AMT"] = ((decimal)drw["TRADING_AMT"] * msBsc.AppLogic.Cfg.SystemSet.oSystemSet.getSysSetVal<decimal>("_SHOP_BUY_SCORE_AMT_PER")) / 2;
                drnewtrad3["TRADING_SID"] = "已支付";
                drnewtrad3["TRADING_DESC"] = "积分销售分成给推广商（分成标准" + msBsc.AppLogic.Cfg.SystemSet.oSystemSet.getSysSetVal<string>("_SHOP_BUY_SCORE_AMT_PER") + "）";
                dstm.Tables[0].Rows.Add(drnewtrad3);


                DataRow drnewtrad4 = dstm.Tables[0].NewRow();
                drnewtrad4["CHARGE_TRADING_ID"] = this.DataObj.NewID();
                drnewtrad4["ACCOUNT_NO"] = dstm6.Tables[0].Rows[0]["FWDUSER_NME"].ToString();
                drnewtrad4["ACCOUNT_NME"] = dstm6.Tables[0].Rows[0]["FWDUSER_NME"].ToString();
                drnewtrad4["USER_TYPE_CID"] = "4";
                drnewtrad4["PAY_DIR"] = "收入";//收付：收入、支出
                drnewtrad4["CHARGE_SRC_CID"] = "商城帐户";//费用来源：商城帐户，在线支付，推广账户
                drnewtrad4["TRADING_NO"] = drw["TRADING_NO"];
                drnewtrad4["TRADING_NME"] = drw["TRADING_NME"];
                drnewtrad4["TRADING_TYPE_CID"] = "购积分";//交易类型：购物，充值，缴费，提现，销售,购积分,扣点
                drnewtrad4["OTH_ACCOUNT_NO"] = "system";
                drnewtrad4["OTH_ACCOUNT_NME"] = "地接客商城";
                drnewtrad4["TRADING_AMT"] = ((decimal)drw["TRADING_AMT"] * msBsc.AppLogic.Cfg.SystemSet.oSystemSet.getSysSetVal<decimal>("_SHOP_BUY_SCORE_AMT_PER")) / 2;
                drnewtrad4["TRADING_SID"] = "已支付";
                drnewtrad4["TRADING_DESC"] = "积分销售分成给代理商（分成标准" + msBsc.AppLogic.Cfg.SystemSet.oSystemSet.getSysSetVal<string>("_SHOP_BUY_SCORE_AMT_PER") + "）";
                dstm.Tables[0].Rows.Add(drnewtrad4);

            }
        }

    }
}
